package com.zhmsky.config.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

/**
 * @author zhmsky
 * @date 2021/12/2 15:11
 */
@Configuration
public class ShiroConfig {

    //ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        //添加shiro的内置过滤器
        HashMap<String, String> filterMap = new HashMap<>();
        //只有被认证了才能访问
        /*
           anon: 无需认证就可以访问
           authc: 必须认证才能访问
           user: 必须拥有 记住我 才能被访问
           perms: 拥有对某个资源的权限才能被访问
           role: 拥有某个角色权限才能被访问

         */
//        filterMap.put("/user/add","authc");
//        filterMap.put("/user/delete","authc");

        //用户认证
        filterMap.put("/user/*","authc");
        // 用户授权
        filterMap.put("/user/add","perms[user:add]");
        filterMap.put("/user/delete","perms[user:delete]");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);

        //没有认证
        shiroFilterFactoryBean.setLoginUrl("/ToLogin");
        //没有授权
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthoriz");

        return shiroFilterFactoryBean;
    }

    //DefaultWebSecurityManager 管理realm对象
    @Bean(name="securityManager")
    public DefaultWebSecurityManager getWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联realm对象
        securityManager.setRealm(userRealm);
        return securityManager;
    }


    //创建realm对象 (需要自定义)
    @Bean(name="userRealm")
    public UserRealm getUserRealm(){
        return new UserRealm();
    }

    //整合shiro和thymeleaf
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }

}
